import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'

interface ProductSearchState {
  loading: boolean,
  error: null | unknown,
  data: any,
  pagination: any
}

// 初始化数据
const initialState: ProductSearchState = {
  loading: false,
  error: null,
  data: null,
  pagination: null
}

// 第一个参数 命名空间/action
export const searchProduct = createAsyncThunk(
  "productSearchSlice/getProductDetail",
  async (paramaters: {
    keywords: string | undefined, 
    nextPage: number | string, 
    pageSize: number | string
  }) => {
      let url = `https://mock.mengxuegu.com/mock/61c70e2ebba8817f8a413580/tourism_website/api/touristRoutes?pageNumber=${paramaters.nextPage}&pageSize=${paramaters.pageSize}`
      if (paramaters.keywords) {
        url += `&keywords=${paramaters.keywords}`
      }
      const response = await axios.get(url)
      console.log("详情111", response)

      return {
        data: response.data.data,
        pagination: response.data.pagination
      }
  }
)

export const productSearchSlice = createSlice({
  name: 'productSearchSlice', // 命名空间名称
  initialState, // 初始化数据
  reducers: {
  
  }, // 这里的reducer是把action和reducer捆绑在了一起.所以不需要在单独定义action,这里的reducer是个对象
  extraReducers: {
    [searchProduct.pending.type]: (state) => {
      // 原始写法
      // return { ...state, loading: true }
      state.loading = true  // immer
    },
    // reducer中已经提前定义好了action的参数
    // 请求成功
    [searchProduct.fulfilled.type]: (state, action) => {
      // action.payload数据是从searchProduct return出来的  
      state.data = action.payload.data // 数据列表
      state.pagination = action.payload.pagination  // 分页
      state.loading = false
      state.error = null
    },
    // 请求失败
    [searchProduct.rejected.type]: (state, action: PayloadAction<unknown | null>) => {
      state.loading = false
      state.error = action.payload
    }
  }
})